package jd.se.admin.BookControl;

import jd.se.common.Utils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class BookService {
    public List<Book> getBookList() {

        SqlSession sess = Utils.openSession();
        try{
            BookDao dao = sess.getMapper(BookDao.class);
            List<Book> BookList = dao.findBookList();
            sess.commit();
            return BookList;
        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("无法获取待审核书籍！",e);
        }finally {
            sess.close();
        }
    }
    public void addBook(BookDto b){
        SqlSession sess = Utils.openSession();
        try{
            BookDao dao = sess.getMapper(BookDao.class);
            dao.addBook(b);
            sess.commit();
        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("添加书籍失败！",e);
        }finally {
            sess.close();
        }
    }

    public void acceptBook(BookDto dto) {
        SqlSession sess = Utils.openSession();
        try{
            BookDao dao=sess.getMapper(BookDao.class);
            dao.acceptBook(dto.getB_id());
            sess.commit();
        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("添加书籍失败！",e);
        }finally {
            sess.close();
        }
    }

    public void deleteBook(BookDto dto) {
        SqlSession sess = Utils.openSession();
        try{
            BookDao dao = sess.getMapper(BookDao.class);
            if(dao.is_borrowed(dto.getB_id())>0)
            throw new RuntimeException("书籍已被借出,无法删除!");
            else
                dao.deleteBook(dto.getB_id());
            sess.commit();
        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("操作失败！",e);
        }finally {
            sess.close();
        }
    }
    public List<Book> searchBook(BookDto dto) {
        SqlSession sess = Utils.openSession();
        try{
            BookDao dao = sess.getMapper(BookDao.class);
            List<Book> BookList = dao.searchBook(dto.getB_id());
            sess.commit();
            return BookList;
        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("无法获取待审核书籍！",e);
        }finally {
            sess.close();
        }
    }
}
